package main

import (
	"fmt"
	"sync"
	"time"
)

var group sync.WaitGroup

func addNum(intChan chan int) {
	for i := 2; i < 200000; i++ {
		intChan <- i
	}
	close(intChan)
	group.Done()
}

func primeNum(intChan chan int, primeChan chan int, exitChan chan bool) {
	for n := range intChan {
		var flag = true
		for i := 2; i < n; i++ {
			if n%i == 0 {
				flag = false
				break
			}
		}
		if flag {
			primeChan <- n
		}
	}
	exitChan <- true
	group.Done()
}

func main() {
	intChan := make(chan int, 1000)   //存放数据管道
	primeChan := make(chan int, 20000) //存放素数管道
	exitChan := make(chan bool, 16)   //退出条件管道

	start := time.Now().Unix()

	group.Add(1)
	go addNum(intChan)

	for i := 0; i < 16; i++ {
		group.Add(1)
		go primeNum(intChan, primeChan, exitChan)
	}

	group.Add(1)
	go func() {
		for i := 0; i < 16; i++ {
			<-exitChan
		}
		close(primeChan) //当取不到exitChan的数据后，关闭primeChan
		group.Done()
	}()

	group.Wait()
	end := time.Now().Unix()
	fmt.Println(end - start)
}
